import 'package:efood_multivendor/controller/auth_controller.dart';
import 'package:efood_multivendor/controller/cart_controller.dart';
import 'package:efood_multivendor/controller/search_controller.dart';
import 'package:efood_multivendor/data/model/response/keyword_suggestion_model.dart';
import 'package:efood_multivendor/helper/responsive_helper.dart';
import 'package:efood_multivendor/helper/size_config.dart';
import 'package:efood_multivendor/util/dimensions.dart';
import 'package:efood_multivendor/util/styles.dart';
import 'package:efood_multivendor/view/base/cart_view.dart';
import 'package:efood_multivendor/view/base/custom_button.dart';
import 'package:efood_multivendor/view/base/custom_snackbar.dart';
import 'package:efood_multivendor/view/screens/search/widget/filter_widget.dart';
import 'package:efood_multivendor/view/screens/search/widget/search_result_widget.dart';
import 'package:flutter/material.dart' hide SearchController;
import 'package:flutter_feather_icons/flutter_feather_icons.dart';
import 'package:flutter_typeahead/flutter_typeahead.dart';
import 'package:get/get.dart';

import '../../../controller/restaurant_controller.dart';
import '../../../data/model/response/restaurant_model.dart';
import '../../../helper/route_helper.dart';
import '../restaurant/restaurant_screen.dart';

class SearchScreen extends StatefulWidget {
  @override
  _SearchScreenState createState() => _SearchScreenState();
}

class _SearchScreenState extends State<SearchScreen> {
  final TextEditingController _searchController = TextEditingController();
  bool _isLoggedIn = false;
  @override
  void initState() {
    super.initState();
    _isLoggedIn = Get.find<AuthController>().isLoggedIn();
    Get.find<SearchController>().getHistoryList();
  }

  @override
  Widget build(BuildContext context) {
    _searchController.selection = TextSelection.fromPosition(
        TextPosition(offset: _searchController.text.length));
    return GetBuilder<SearchController>(builder: (searchController) {
      return WillPopScope(
        onWillPop: () async {
          searchController.setRestaurant(true);
          if (Get.find<SearchController>().isSearchMode) {
            return true;
          } else {
            Get.find<SearchController>().setSearchMode(true);
            return false;
          }
        },
        child: GetBuilder<CartController>(builder: (cartController) {
          return Scaffold(
            resizeToAvoidBottomInset: false,
            body: CartView(
                SafeArea(
                    child: Padding(
                  padding: EdgeInsets.symmetric(
                      vertical: Dimensions.PADDING_SIZE_SMALL),
                  child:
                      GetBuilder<SearchController>(builder: (searchController) {
                    _searchController.text = searchController.searchText;
                    return Column(children: [
                      Center(
                          child: SizedBox(
                              width: Dimensions.WEB_MAX_WIDTH,
                              child: Row(children: [
                                IconButton(
                                    padding: EdgeInsets.zero,
                                    onPressed: () {
                                      searchController.setRestaurant(true);
                                      Get.back();
                                    },
                                    icon: Icon(Icons.arrow_back_ios)),
                                SizedBox(
                                    width: Dimensions.PADDING_SIZE_EXTRA_SMALL),
                                Expanded(
                                    child: Hero(
                                  tag: 'search_food_or_restaurant'.tr,
                                  child: Container(
                                    padding: EdgeInsets.all(
                                        Dimensions.PADDING_SIZE_SMALL),
                                    alignment: Alignment.topCenter,
                                    child: Material(
                                      shape: RoundedRectangleBorder(
                                          borderRadius: BorderRadius.circular(
                                              Dimensions.RADIUS_SMALL)),
                                      child: SizedBox(
                                          width: Dimensions.WEB_MAX_WIDTH,
                                          child: TypeAheadField(
                                            textFieldConfiguration:
                                                TextFieldConfiguration(
                                              controller: _searchController,
                                              onSubmitted: (keyword) {
                                                searchController
                                                    .searchData(keyword);
                                              },
                                              textInputAction:
                                                  TextInputAction.search,
                                              onEditingComplete: () {
                                                _actionSearch(
                                                    searchController, true);
                                                FocusScope.of(context)
                                                    .unfocus();
                                              },
                                              autofocus: true,
                                              textCapitalization:
                                                  TextCapitalization.words,
                                              keyboardType: TextInputType.text,
                                              decoration: InputDecoration(
                                                hintText:
                                                    'search_food_or_restaurant'
                                                        .tr,
                                                hintStyle: sfRegular.copyWith(
                                                    fontSize: Dimensions
                                                        .fontSizeSmall,
                                                    color: Theme.of(context)
                                                        .disabledColor),
                                                border: OutlineInputBorder(
                                                    borderRadius:
                                                        BorderRadius.circular(
                                                            Dimensions
                                                                .RADIUS_SMALL),
                                                    borderSide:
                                                        BorderSide.none),
                                                filled: true,
                                                fillColor:
                                                    Theme.of(context).cardColor,
                                                isDense: true,
                                                suffixIcon: IconButton(
                                                  onPressed: () {
                                                    _actionSearch(
                                                        searchController, true);
                                                    FocusScope.of(context)
                                                        .unfocus();
                                                  },
                                                  icon: Icon(Icons.search),
                                                ),
                                              ),
                                              style: Theme.of(context)
                                                  .textTheme
                                                  .headlineMedium
                                                  ?.copyWith(
                                                    color: Theme.of(context)
                                                        .textTheme
                                                        .bodyMedium
                                                        ?.color,
                                                    fontSize: Dimensions
                                                        .fontSizeLarge,
                                                  ),
                                            ),
                                            suggestionsCallback:
                                                (keyword) async {
                                              Future.delayed(
                                                  Duration(milliseconds: 300),
                                                  () {});
                                              List<KeywordSuggestionModel>
                                                  results = await Get.find<
                                                          SearchController>()
                                                      .searchKeyword(
                                                          context, keyword);
                                              return results;
                                            },
                                            getImmediateSuggestions: true,
                                            hideOnError: true,
                                            hideOnEmpty: true,
                                            hideSuggestionsOnKeyboardHide: true,
                                            hideOnLoading: true,
                                            autoFlipDirection: true,
                                            itemBuilder: (context,
                                                KeywordSuggestionModel
                                                    keyword) {
                                              return Padding(
                                                padding: EdgeInsets.all(
                                                    Dimensions
                                                        .PADDING_SIZE_SMALL),
                                                child: Row(children: [
                                                  Icon(keyword.type == "item"
                                                      ? Icons.restaurant
                                                      : Icons.home),
                                                  SizedBox(width: 2.w),
                                                  Expanded(
                                                    child: Text(
                                                        keyword.keyword ?? '',
                                                        maxLines: 2,
                                                        overflow: TextOverflow
                                                            .ellipsis,
                                                        style: Theme.of(context)
                                                            .textTheme
                                                            .headlineSmall
                                                            ?.copyWith(
                                                              color: Theme.of(
                                                                      context)
                                                                  .textTheme
                                                                  .bodyMedium
                                                                  ?.color,
                                                              fontSize: Dimensions
                                                                  .fontSizeLarge,
                                                            )),
                                                  ),
                                                ]),
                                              );
                                            },
                                            onSuggestionSelected:
                                                (KeywordSuggestionModel
                                                    keyword) async {
                                              if (keyword.type == "item") {
                                                searchController.searchData(
                                                    keyword.keyword ?? '');
                                              } else {
                                                searchController.loading(true);
                                                Restaurant? restaurants =
                                                    await Get.find<
                                                            RestaurantController>()
                                                        .getRestaurantDetails(
                                                            Restaurant(
                                                                id: keyword
                                                                    .restaurantId),
                                                            'search');
                                                Get.toNamed(
                                                    RouteHelper
                                                        .getRestaurantRoute(
                                                            keyword
                                                                .restaurantId!),
                                                    arguments: RestaurantScreen(
                                                        restaurant:
                                                            restaurants!));
                                                searchController.loading(false);
                                              }
                                            },
                                          )),
                                    ),
                                  ),
                                )),
                                CustomButton(
                                  onPressed: () {
                                    searchController.setRestaurant(true);
                                    searchController.isSearchMode
                                        ? Get.back()
                                        : searchController.setSearchMode(true);
                                  },
                                  buttonText: 'cancel'.tr,
                                  transparent: true,
                                  width: 80,
                                ),
                              ]))),
                      SizedBox(height: Dimensions.PADDING_SIZE_EXTRA_SMALL * 3),
                      searchController.isLoading
                          ? Column(
                              mainAxisAlignment: MainAxisAlignment.center,
                              children: [
                                SizedBox(
                                  height: 250,
                                ),
                                Center(child: CircularProgressIndicator()),
                              ],
                            )
                          : Expanded(
                              child: searchController.isSearchMode
                                  ? SingleChildScrollView(
                                      physics: BouncingScrollPhysics(),
                                      padding: EdgeInsets.symmetric(
                                          horizontal:
                                              Dimensions.PADDING_SIZE_SMALL),
                                      child: Center(
                                          child: SizedBox(
                                              width: Dimensions.WEB_MAX_WIDTH,
                                              child: Column(
                                                  crossAxisAlignment:
                                                      CrossAxisAlignment.start,
                                                  children: [
                                                    Padding(
                                                      padding:
                                                          EdgeInsets.symmetric(
                                                              horizontal: 2.w),
                                                      child: (_isLoggedIn &&
                                                              searchController
                                                                      .suggestedFoodList !=
                                                                  null)
                                                          ? Text(
                                                              'popular_searches'
                                                                  .tr,
                                                              style: sfMedium.copyWith(
                                                                  color: Colors
                                                                      .black
                                                                      .withOpacity(
                                                                          0.45),
                                                                  fontSize:
                                                                      Dimensions
                                                                          .fontSizeDefault),
                                                            )
                                                          : SizedBox(),
                                                    ),
                                                    SizedBox(
                                                        height: Dimensions
                                                                .PADDING_SIZE_EXTRA_SMALL *
                                                            2),
                                                    (_isLoggedIn &&
                                                            searchController
                                                                    .suggestedFoodList !=
                                                                null)
                                                        ? searchController
                                                                    .suggestedFoodList
                                                                    ?.isNotEmpty ==
                                                                true
                                                            ? GridView.builder(
                                                                gridDelegate:
                                                                    SliverGridDelegateWithFixedCrossAxisCount(
                                                                  crossAxisCount:
                                                                      ResponsiveHelper.isMobile(
                                                                              context)
                                                                          ? 4
                                                                          : 4,
                                                                  childAspectRatio:
                                                                      (1 /
                                                                          0.35),
                                                                  mainAxisSpacing:
                                                                      Dimensions
                                                                          .PADDING_SIZE_SMALL,
                                                                  crossAxisSpacing:
                                                                      Dimensions
                                                                          .PADDING_SIZE_SMALL,
                                                                ),
                                                                padding: EdgeInsets
                                                                    .all(Dimensions
                                                                        .PADDING_SIZE_SMALL),
                                                                physics:
                                                                    NeverScrollableScrollPhysics(),
                                                                shrinkWrap:
                                                                    true,
                                                                itemCount: searchController
                                                                        .suggestedFoodList
                                                                        ?.length ??
                                                                    0,
                                                                itemBuilder:
                                                                    (context,
                                                                        index) {
                                                                  return InkWell(
                                                                    onTap: () {
                                                                      searchController.searchData(searchController
                                                                          .suggestedFoodList![
                                                                              index]
                                                                          .name!);
                                                                    },
                                                                    child:
                                                                        Container(
                                                                      padding: EdgeInsets.symmetric(
                                                                          horizontal:
                                                                              8,
                                                                          vertical:
                                                                              1),
                                                                      decoration:
                                                                          BoxDecoration(
                                                                        color: Color(
                                                                            0x3DA8A8A8),
                                                                        borderRadius:
                                                                            BorderRadius.circular(Dimensions.RADIUS_SMALL),
                                                                      ),
                                                                      child:
                                                                          Center(
                                                                        child:
                                                                            Text(
                                                                          searchController.suggestedFoodList?[index].name ??
                                                                              '',
                                                                          style: sfMedium.copyWith(
                                                                              color: Colors.black.withOpacity(0.7),
                                                                              fontSize: Dimensions.fontSizeSmall),
                                                                          maxLines:
                                                                              1,
                                                                          overflow:
                                                                              TextOverflow.ellipsis,
                                                                        ),
                                                                      ),
                                                                    ),
                                                                  );
                                                                },
                                                              )
                                                            : Padding(
                                                                padding: EdgeInsets
                                                                    .only(
                                                                        top:
                                                                            10),
                                                                child: Text(
                                                                    'no_suggestions_available'
                                                                        .tr))
                                                        : SizedBox(),
                                                    SizedBox(
                                                        height: Dimensions
                                                            .PADDING_SIZE_LARGE),
                                                    Padding(
                                                      padding:
                                                          EdgeInsets.symmetric(
                                                              horizontal: 2.w),
                                                      child: searchController
                                                                  .historyList
                                                                  .length >
                                                              0
                                                          ? Row(
                                                              mainAxisAlignment:
                                                                  MainAxisAlignment
                                                                      .spaceBetween,
                                                              children: [
                                                                  Text(
                                                                      'recent_searches'
                                                                          .tr,
                                                                      style: sfMedium.copyWith(
                                                                          color: Colors.black.withOpacity(
                                                                              0.45),
                                                                          fontSize:
                                                                              Dimensions.fontSizeDefault)),
                                                                  InkWell(
                                                                    onTap: () =>
                                                                        searchController
                                                                            .clearSearchAddress(),
                                                                    child:
                                                                        Padding(
                                                                      padding: EdgeInsets.symmetric(
                                                                          vertical: Dimensions
                                                                              .PADDING_SIZE_SMALL,
                                                                          horizontal:
                                                                              4),
                                                                      child: Text(
                                                                          'clear_all'
                                                                              .tr,
                                                                          style:
                                                                              sfRegular.copyWith(
                                                                            fontSize:
                                                                                Dimensions.fontSizeSmall,
                                                                            color:
                                                                                Theme.of(context).disabledColor,
                                                                          )),
                                                                    ),
                                                                  ),
                                                                ])
                                                          : SizedBox(),
                                                    ),
                                                    Padding(
                                                      padding:
                                                          EdgeInsets.symmetric(
                                                              horizontal: 2.w),
                                                      child: ListView.builder(
                                                        itemCount:
                                                            searchController
                                                                .historyList
                                                                .length,
                                                        physics:
                                                            NeverScrollableScrollPhysics(),
                                                        shrinkWrap: true,
                                                        itemBuilder:
                                                            (context, index) {
                                                          return Column(
                                                              children: [
                                                                Row(children: [
                                                                  Expanded(
                                                                    child:
                                                                        InkWell(
                                                                      onTap: () =>
                                                                          searchController
                                                                              .searchData(searchController.historyList[index]),
                                                                      child:
                                                                          Padding(
                                                                        padding:
                                                                            EdgeInsets.symmetric(vertical: Dimensions.PADDING_SIZE_EXTRA_SMALL),
                                                                        child:
                                                                            Row(
                                                                          children: [
                                                                            Icon(
                                                                              FeatherIcons.clock,
                                                                              size: 3.5.w,
                                                                              color: Colors.black.withOpacity(0.45),
                                                                            ),
                                                                            SizedBox(width: 4.w),
                                                                            Text(
                                                                              searchController.historyList[index],
                                                                              style: sfRegular.copyWith(color: Theme.of(context).disabledColor),
                                                                              maxLines: 1,
                                                                              overflow: TextOverflow.ellipsis,
                                                                            ),
                                                                          ],
                                                                        ),
                                                                      ),
                                                                    ),
                                                                  ),
                                                                  InkWell(
                                                                    onTap: () =>
                                                                        searchController
                                                                            .removeHistory(index),
                                                                    child:
                                                                        Padding(
                                                                      padding: EdgeInsets.symmetric(
                                                                          vertical:
                                                                              Dimensions.PADDING_SIZE_EXTRA_SMALL),
                                                                      child: Icon(
                                                                          Icons
                                                                              .close,
                                                                          color: Theme.of(context)
                                                                              .disabledColor,
                                                                          size:
                                                                              20),
                                                                    ),
                                                                  )
                                                                ]),
                                                                index !=
                                                                        searchController.historyList.length -
                                                                            1
                                                                    ? Divider()
                                                                    : SizedBox(),
                                                              ]);
                                                        },
                                                      ),
                                                    ),
                                                  ]))),
                                    )
                                  : SearchResultWidget(
                                      searchText:
                                          _searchController.text.trim())),
                    ]);
                  }),
                )),
                "",
                restaurantId: Get.find<CartController>().currentSuggestion),
            extendBody: true,
            bottomNavigationBar: cartController.cartview,
          );
        }),
      );
    });
  }

  void _actionSearch(SearchController searchController, bool isSubmit) {
    if (searchController.isSearchMode || isSubmit) {
      if (_searchController.text.trim().isNotEmpty) {
        searchController.searchData(_searchController.text.trim());
      } else {
        showCustomSnackBar('search_food_or_restaurant'.tr);
      }
    } else {
      List<double> _prices = [];
      if (!searchController.isRestaurant) {
        searchController.allProductList
            ?.forEach((product) => _prices.add(product.price!));
        _prices.sort();
      }
      double _maxValue =
          _prices.length > 0 ? _prices[_prices.length - 1] : 1000;
      Get.dialog(FilterWidget(
          maxValue: _maxValue, isRestaurant: searchController.isRestaurant));
    }
  }
}
